import re
from typing import Union, List
from datetime import datetime as dt, timedelta, timezone
from collections import OrderedDict
from time import mktime

from dateutil.parser import parse, ParserError
from nltk.tokenize import word_tokenize


def message_segment(data: str) -> List:
    """
    数据分词
    :param data: 数据列表
    :return: 使用 Natural Language Toolkit分词库,查找数据相似度最高数据
    """
    tokens = word_tokenize(data)
    # 过滤除中英文及数字以外的其他字符 https://zhuanlan.zhihu.com/p/144216817
    rc = re.compile(r"[^\u4e00-\u9fa5^a-z^A-Z^0-9]")

    # 一般转化为小写来分析
    return [word.lower() for word in tokens if not rc.match(word)]


def format_string_len(data: str, len_size: int = 480, newline_count: int = 3):
    """
    :param data: 字符串数据
    :param len_size:  字符串长度
    :param newline_count:  换行符数量
    :return:
    """
    if len(data) > len_size:
        if data.count('\n'):
            format_string, _, r = data[:len_size].rpartition('\n')
            if format_string.count('\n') >= newline_count:
                data = '\n'.join(format_string.split('\n')[:newline_count])
        else:
            r = re.compile(r'(.*)[,|\?|&].*')
            format_string = data[:len_size]
            try:
                data = r.search(format_string).group(1)
            except AttributeError:
                data = format_string
    return data


def time_compare(begin_time: Union[dt, str], end_time: Union[dt, str]):
    try:
        if parse(end_time) > dt.now() > parse(begin_time):
            return True
        else:
            return False
    except (TypeError, ParserError):
        return False


def collection(str_or_ts, cst=True, dtype=None):
    """
    utc: Coordinated Universal Time  世界协调时间
    cst: China Standard Time UTC+8:00 中国标准时间  utc + 08:000
    系统本地时间  local_time 一般采用 utc + 08:000 = cst 中国标准时间

    :param str_or_ts: string|timetuple
    :param cst:   True or False
    :param dtype: string|datetime|struct_time|timestramp 时间
    :return: dict 所有没有表明时区时间类型
    """
    dt_str = None
    res = OrderedDict()
    if isinstance(str_or_ts, str):
        dt_str = parse(str_or_ts).strftime("%Y-%m-%d %X.%f")
    elif isinstance(str_or_ts, dt):
        dt_str = str_or_ts.strftime("%Y-%m-%d %X.%f")
    elif isinstance(str_or_ts, (int, float)):
        dt_str = dt.fromtimestamp(str_or_ts).strftime("%Y-%m-%d %X.%f")

    if dt_str:
        if isinstance(cst, bool):
            if cst:
                dt_cst_obj = parse(dt_str).replace(tzinfo=timezone(timedelta(hours=8)))
                dt_utc_obj = dt_cst_obj.astimezone(timezone(timedelta(hours=0)))
            else:
                dt_utc_obj = parse(dt_str).replace(tzinfo=timezone(timedelta(hours=0)))
                dt_cst_obj = dt_utc_obj.astimezone(timezone(timedelta(hours=8)))
            res['cst_str'] = dt_cst_obj.strftime("%Y-%m-%d %X")
            res['cst_timezone_str'] = dt_cst_obj.strftime("%Y-%m-%d %X")
            res['cst_dt'] = dt_cst_obj
            res['cst_ts'] = int(mktime(dt_cst_obj.timetuple()))
            res['cst_ts_ms'] = int(mktime(dt_cst_obj.timetuple()) * 1000.0 + dt_cst_obj.microsecond / 1000.0)

            res['utc_str'] = dt_utc_obj.strftime("%Y-%m-%d %X")
            res['utc_timezone_str'] = dt_utc_obj.strftime("%Y-%m-%d %X.%f %z")
            res['utc_dt'] = dt_utc_obj
            res['utc_ts'] = int(mktime(dt_utc_obj.timetuple()))
            # 毫秒
            res['utc_ts_ms'] = int(mktime(dt_utc_obj.timetuple()) * 1000.0 + dt_utc_obj.microsecond / 1000.0)
            # 微妙
            res['utc_ts_ns'] = int(mktime(dt_utc_obj.timetuple()) * 100000.0 + dt_utc_obj.microsecond / 100000.0)
    if dtype in dict(res).keys():
        return dict(res).get(dtype)
    else:
        return dict(res)


if __name__ == '__main__':
    from pprint import pprint

    pprint(collection('2023-03-27T04:10:00.000Z', cst=False, dtype='cst_str'))
